<?php

namespace App\Classes\Injection;

use App\Models\Entity\Assets\Assets;
use App\Models\Entity\Assets\AssetStream;
use App\Models\Injection\InjectAssetiHistory;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Log;
use DB;
use Storage;

/**
 * 媒资注入自定义类
 */
class AssetiInjection
{

    /**
     * [$injectionWhere 注入的条件]
     * @var array
     */
    protected $injectionWhere = ['online_status' => 1];

    /**
     * [$injectVassetiHistory description]
     * @var [type]
     */
    protected $injectVassetiHistory;

    /**
     * [$ids description]
     * @var [type]
     */
    protected $ids;

    /**
     * { 判断是单个剧集还是多个剧集 }
     *
     * @var        boolean
     */
    public $flag = false;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct( $ids = null)
    {
        $this->ids                  = $ids;
        if (!is_null($ids)) {
            if (is_array($ids)) {
                $this->injectionWhere = ['inject_datetime' => 0];
                $this->flag           = true;
            }
        }
    }

    /**
     * 发起媒资注入
     *
     * @return contnet
     */
    public function handle()
    {

        $vassetis = Assets::whereIn('id', $this->ids)->get();

        // 注入媒资总数
        $injectionVasseticount = count($vassetis);
        // 错误的行数
        $errorRow = [];

        $success_count = 0;

        foreach ($vassetis as $vasseti) {
            $this->injectVassetiHistory                 = new InjectAssetiHistory;
            $this->injectVassetiHistory->batch_no       = date('YmdHis');
            $this->injectVassetiHistory->user_id = Admin::user()->id;
            $this->injectVassetiHistory->task_no        = date('YmdHis') . uniqid();
            $this->injectVassetiHistory->asset_id     = $vasseti->id;
            $this->injectVassetiHistory->spasset_id     = $vasseti->spasset_id;
            // 开始时间
            $starttime = microtime(true);
            // 开始使用内存
            $startMemory = memory_get_usage();

            //判断注入地区
            $media_injection_place = config('custom.base.media_injection.place');

            switch ($media_injection_place) {
                case 'guizhou':
                    $xml = $this->getXmlDataGuiZhou($vasseti);

                    $rs  = $this->httpPostGuiZhou($this->injectVassetiHistory->task_no,$vasseti->spid,$xml);

                    if($rs['done_post_status']=='1'){
                        $success_count++;
                    }else{
                        $errorRow[] = $vasseti->id;
                    }
                    break;
                case 'heilongjiang':

                    break;

            }

            // 结束时间
            $endtime        = microtime(true);
            $consuming_time = round($endtime - $starttime, 4);
            $endMemory      = memory_get_usage();
            $usedMemory     = ($endMemory - $startMemory) / 1024;


            $this->injectVassetiHistory->done_post_status = $rs['done_post_status'];
            $this->injectVassetiHistory->done_post_result = $rs['done_post_result'];
            $this->injectVassetiHistory->post_content    = $rs['post_content'];
            $this->injectVassetiHistory->consuming_time = $consuming_time;
            $this->injectVassetiHistory->used_memory    = $usedMemory;
            $this->injectVassetiHistory->save();

        }

        $flag       = true;
        $errorCount = count($errorRow);
        $message    = '<div style="word-wrap: break-word;">';
        $message .= '发起注入工单总数:';
        $message .= $injectionVasseticount. '<br />';
        $message .= '发起注入工单成功数:';
        $message .= $success_count . '<br />';
        $message .= '发起注入工单失败数:';
        $message .= count($errorRow) . '<br />';
        if ($errorCount > 0) {
            $flag = false;
            $message .= '注入失败的媒资id:' . implode(',', $errorRow) . '<br />';
        }
        $message .= '</div>';
        //通过标志位判断前端返回时成功还是失败
        if ($flag) {
            $message = '<div class="alert alert-success">' . $message . '</div>';
        } else {
            $message = '<div class="alert alert-error">' . $message . '</div>';
        }

        return $message;
    }


    /**
     * 获得媒资注入数据
     *
     * @return contnet
     */
    public function getInjectDate()
    {
        $vassetis = Assets::with(['stream'])->whereIn('id', $this->ids)->get();

        // 媒资总数
        $injectionVasseticount = count($vassetis);
        // 错误的行数
        $errorRow = [];

        $success_count = 0;

        foreach ($vassetis as $vasseti) {
            $this->injectVassetiHistory                 = new InjectAssetiHistory;
            $this->injectVassetiHistory->batch_no       = date('YmdHis');
            $this->injectVassetiHistory->user_id = Admin::user()->id;
            $this->injectVassetiHistory->task_no        = date('YmdHis') . uniqid();
            $this->injectVassetiHistory->asset_id     = $vasseti->id;
            $this->injectVassetiHistory->spasset_id     = $vasseti->spasset_id;
            // 开始时间
            $starttime = microtime(true);
            // 开始使用内存
            $startMemory = memory_get_usage();

            if(!isset($vasseti->stream->ogroup_asset_id) || empty($vasseti->stream->ogroup_asset_id)){
                $errorRow[] ="媒资ID: ". $vasseti->id ."错误信息: 缺少渠道方媒资ID ogroup_asset_id,没有注入数据,请确认注入完成后再操作";
                $rs = ['done_post_status'=>0,'done_post_result'=>'缺少渠道方媒资ID: ogroup_asset_id'];
                continue;
            }

            //判断注入地区
            $media_injection_place = config('custom.base.media_injection.place');

            switch ($media_injection_place) {

                case 'heilongjiang':
                    $config = config('custom.base.media_injection.heilongjiang.'.$vasseti->spid);
                    $config['titleAssetId'] = $vasseti->stream->ogroup_asset_id;
                    $rs = self::getHeilongjiangAssetData($config);

                    if($rs['done_post_status']=='1'){
                        $success_count++;
                        $vasseti->stream->ogroup_asset_data = $rs['done_post_result'];
                        $check_rs = $this->checkHeilongjiangAssetData($vasseti);
                    }else{
                        $errorRow[] = $rs['done_post_result'];
                        $check_rs = ['task_status'=>0,'pic_state'=>0,'series_state'=>0,'program_state'=>0,'movie_state'=>0];
                    }
                    break;
            }

            // 结束时间
            $endtime        = microtime(true);
            $consuming_time = round($endtime - $starttime, 4);
            $endMemory      = memory_get_usage();
            $usedMemory     = ($endMemory - $startMemory) / 1024;

            $this->injectVassetiHistory->done_post_status = $rs['done_post_status'];
            $this->injectVassetiHistory->done_post_result = $rs['done_post_result'];
            $this->injectVassetiHistory->post_content    = $rs['post_content'];
            $this->injectVassetiHistory->task_status = $check_rs['task_status'];
            $this->injectVassetiHistory->pic_state = $check_rs['pic_state'];
            $this->injectVassetiHistory->series_state = $check_rs['series_state'];
            $this->injectVassetiHistory->program_state = $check_rs['program_state'];
            $this->injectVassetiHistory->movie_state = $check_rs['movie_state'];
            $this->injectVassetiHistory->consuming_time = $consuming_time;
            $this->injectVassetiHistory->used_memory    = $usedMemory;
            $this->injectVassetiHistory->save();

        }

        $flag       = true;
        $errorCount = count($errorRow);
        $message    = '<div style="word-wrap: break-word;">';
        $message .= '发起同步总数:';
        $message .= $injectionVasseticount. '<br />';
        $message .= '同步成功数:';
        $message .= $success_count . '<br />';
        $message .= '同步失败数:';
        $message .= count($errorRow) . '<br />';
        if ($errorCount > 0) {
            $message .= '导入失败数据:<br>';
            $flag = false;
            foreach ($errorRow as $error){
                $message .= $error.'<br>';
            }
        }
        $message .= '</div>';
        //通过标志位判断前端返回时成功还是失败
        if ($flag) {
            $message = '<div class="alert alert-success">' . $message . '</div>';
        } else {
            $message = '<div class="alert alert-error">' . $message . '</div>';
        }

        return $message;
    }

    /*
     * 黑龙江媒资数据
     */
    public static function getHeilongjiangAssetData($config){
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->standalone = true;
        $GetItemData =  $dom->createElement('GetItemData');
        $GetItemData->setAttribute('portalId', '102');
        $GetItemData->setAttribute('client', $config['clientId']);
        $GetItemData->setAttribute('account', $config['accountId']);
        $GetItemData->setAttribute('titleAssetId', $config['titleAssetId']);

        // 把<ADI>元素追加到文档里面
        $dom->appendChild($GetItemData);

        $xml = $dom->saveXML();

        $header = array(
            "cache-control: no-cache",
            "content-type: application/xml"
        );
        $api_url = $config['api']."GetItemData?dataType=json";
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $xml,
            CURLOPT_HTTPHEADER => $header,
        ));
        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        $rs = array();
        $rs['post_content'] = $xml;
        if ($err) {
            $rs['done_post_status'] = 0;
            $rs['done_post_result'] = 'Curl error no: '.curl_errno($curl) .' Curl error Msg: ' . curl_error($curl);
        } else {
            $rs['done_post_result'] = $response;
            $json_data = json_decode($response,true);
            if(isset($json_data['code'])){
                $rs['done_post_status'] = 0;
            }else{
                $rs['done_post_status'] = 1;
            }
        }
        return $rs;
    }

    /*
     * 黑龙江媒资播放串数据
     */
    public static function getHeilongjiangAssetSelectionStart($config){
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->standalone = true;
        $SelectionStart =  $dom->createElement('SelectionStart');
        $SelectionStart->setAttribute('portalId', '102');
        $SelectionStart->setAttribute('client', $config['clientId']);
        $SelectionStart->setAttribute('account', $config['accountId']);
        $SelectionStart->setAttribute('titleAssetId', $config['titleAssetId']);

        // 把<ADI>元素追加到文档里面
        $dom->appendChild($SelectionStart);

        $xml = $dom->saveXML();

        $header = array(
            "cache-control: no-cache",
            "content-type: application/xml"
        );
        $api_url = $config['api']."SelectionStart?dataType=json";
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $xml,
            CURLOPT_HTTPHEADER => $header,
        ));
        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        $rs = array();
        $rs['post_content'] = $xml;
        if ($err) {
            $rs['done_post_status'] = 0;
            $rs['done_post_result'] = 'Curl error no: '.curl_errno($curl) .' Curl error Msg: ' . curl_error($curl);
        } else {
            $rs['done_post_result'] = $response;
            $json_data = json_decode($response,true);
            if(isset($json_data['code'])){
                $rs['done_post_status'] = 0;
            }else{
                $rs['done_post_status'] = 1;
            }
        }
        return $rs;
    }


    //校验黑龙江注入媒资数据完成性,修改媒资注入记录表
    /*
     * 暂未完善
     */
    public function checkHeilongjiangAssetData($asset){
        $data = ['task_status'=>0,'pic_state'=>0,'series_state'=>0,'program_state'=>0,'movie_state'=>0];
        $ogroup_data = json_decode($asset->stream->ogroup_asset_data,true);
        if($ogroup_data['selectableItem']['status'] == "1"){
            $data['task_status'] = 1;
            $data['pic_state'] = 1;
            $data['series_state'] = 1;
            $data['program_state'] = 1;
            $data['movie_state'] = 1;
        }

        //如果注入结果校验通过,更新注入数据
        if($data['task_status'] == 1){
            //更新媒资回调信息
            $stream = AssetStream::where('asset_id', $asset->id)->first();
            if (!$stream) {
                AssetStream::create([
                    'asset_id' => $asset->id,
                    'ogroup_asset_id'=>$asset->stream->ogroup_asset_id,
                    'ogroup_asset_data'=>$asset->stream->ogroup_asset_data
                ]);
            }else{
                AssetStream::where('asset_id', $asset['id'])->update([
                    'ogroup_asset_id'=>$asset->stream->ogroup_asset_id,
                    'ogroup_asset_data'=>$asset->stream->ogroup_asset_data
                ]);
            }

            $update['inject_datetime'] = time();
            Assets::where('id','=',$asset->id)->update($update);
        }
        return $data;
    }

    //自动数据同步任务
    public static function updateHeilongjiangDataToAsset(){
        $configs = config('custom.base.media_injection.heilongjiang');
        foreach ($configs as $sp_no => $conf){
            $rs = self::getHeilongjiangAllAssetData($conf);
            if($rs['done_post_status'] == 0){
                Log::info("黑龙江数据同步接口报错,请求数据:".$rs['post_content']."返回数据:".$rs['done_post_result']);
                continue;
            }
            $assest_list = json_decode($rs['done_post_result'],true);
            $assest_list = $assest_list['selectableItemList'];
            foreach ($assest_list as $item){
                $asset = Assets::where("spid",$sp_no)
                      ->where("title",$item['titleBrief'])
                      ->where("inject_datetime","=",0)
                      ->first();
                if(empty($asset)){
                    Log::info("黑龙江数据同步异常,没有匹配到媒资数据,媒资名称:".$item['titleBrief']." 渠道媒资ID:".$item['assetId']);
                    continue;
                }

                //更新媒资渠道方信息
                $stream = AssetStream::where('asset_id',$asset->id)->first();
                if(empty($stream)){
                    $stream = new AssetStream();
                }

                //获取播放串数据
                // $conf['titleAssetId'] = $item['assetId'];
                // $rs = self::getHeilongjiangAssetSelectionStart($conf);
                // if($rs['done_post_status'] == 0){
                //     Log::info("黑龙江数据同步接口报错,媒资名称:".$item['titleBrief']."请求数据:".$rs['post_content']."返回数据:".$rs['done_post_result']);
                // }
                // $stream->stream_id = $rs['done_post_result'];

                $stream->asset_id = $asset->id;
                $stream->ogroup_asset_id = $item['assetId'];
                $stream->ogroup_asset_data = json_encode($item);
                $stream->cdn_id = "";
                $rs = $stream->save();
                if(!$rs){
                    Log::info("黑龙江数据同步异常,保存数据失败,媒资名称:".$item['titleBrief']." 渠道媒资ID:".$item['assetId']);
                }
                $update = ['status'=>0];
                $update['inject_datetime'] = time();
                Assets::where('id','=',$asset->id)->update($update);

            }
        }
    }

    /*
     * 黑龙江根据栏目获得所有媒资数据
     */
    public static function getHeilongjiangAllAssetData($config){

        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->standalone = true;
        $GetFolderContents =  $dom->createElement('GetFolderContents');
        $GetFolderContents->setAttribute('portalId', '102');
        $GetFolderContents->setAttribute('mergeTV', '1');
        $GetFolderContents->setAttribute('includeSelectableItem', 'Y');
        $GetFolderContents->setAttribute('maxItems', '1000');
        $GetFolderContents->setAttribute('startAt', '1');
        $GetFolderContents->setAttribute('includeFolderProperties', 'N');
        $GetFolderContents->setAttribute('includeSubFolder', 'Y');
        $GetFolderContents->setAttribute('subIncludeSelectableItem', 'Y');
        $GetFolderContents->setAttribute('assetId', $config['menuId']);
        $GetFolderContents->setAttribute('client', $config['clientId']);
        $GetFolderContents->setAttribute('account', $config['accountId']);

        // 把<ADI>元素追加到文档里面
        $dom->appendChild($GetFolderContents);

        $xml = $dom->saveXML();

        $header = array(
            "cache-control: no-cache",
            "content-type: application/xml"
        );
        $api_url = $config['api']."GetFolderContents?dataType=json";
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $xml,
            CURLOPT_HTTPHEADER => $header,
        ));
        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        $rs = array();
        $rs['post_content'] = $xml;
        if ($err) {
            $rs['done_post_status'] = 0;
            $rs['done_post_result'] = 'Curl error no: '.curl_errno($curl) .' Curl error Msg: ' . curl_error($curl);
        } else {
            $rs['done_post_result'] = $response;
            $json_data = json_decode($response,true);
            if(isset($json_data['code'])){
                $rs['done_post_status'] = 0;
            }else{
                $rs['done_post_status'] = 1;
            }
        }
        return $rs;
    }

    public function httpPostGuiZhou($msgid,$cpid,$xml){

        $guizhou_cp = config('custom.base.media_injection.guizhou_cp');
        // cp_id
        $config_media_injection_cp_id = $guizhou_cp[$cpid]['cpid'];
        // url
        $config_media_injection_url = $guizhou_cp[$cpid]['api'];
        $arr_header = [];
        // $arr_header[] = "Content-type: text/xml; charset=utf-8";
        // $arr_header[] = "SOAPAction:\"\"";

        $post_data = ['msgid'=>$msgid,'cpid'=>$config_media_injection_cp_id,'xml'=>$xml];
        //首先检测是否支持curl
        if (!extension_loaded("curl")) {
            trigger_error("对不起，请开启curl功能模块！", E_USER_ERROR);
        }

        // 初始一个curl会话
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_header);
        //设置超时
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        // 设置url
        curl_setopt($ch, CURLOPT_URL, $config_media_injection_url);
        // TRUE, 将curl_exec()获取的信息以字符串返回, 而不是直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 设置发送方式:post
        curl_setopt($ch, CURLOPT_POST, 1);
        // 设置发送数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        // 执行cURL会话
        $response = curl_exec($ch);
        $rs = array();
        $rs['post_content'] = json_encode($post_data);
        if (curl_errno($ch)) {
            $rs['done_post_status'] = 0;
            $rs['done_post_result'] = 'Curl error no: '.curl_errno($ch) .' Curl error Msg: ' . curl_error($ch);
        }else{
            $rs['done_post_result'] = $response;
            // post的数据为xml字符串，通过 $xml = simplexml_load_string($response);转换成xml对象
            $xml = simplexml_load_string($response);
            if(!$xml){
                $rs['done_post_status'] = 0;
            }else{
                //先把xml转换为simplexml对象，再把simplexml对象转换成 json，再将 json 转换成数组。
                // $value_array = json_decode(json_encode(simplexml_load_string($return_xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
                // 将xml对象转为json
                $response = json_decode(json_encode($xml), true);
                $rs['done_post_status'] = $response['@attributes']['ret'] == "0" ? 1 : 0;
            }

        }
        curl_close($ch);
        return $rs;
    }

    public function getXmlDataGuiZhou($vasseti){

        $guizhou_cp = config('custom.base.media_injection.guizhou_cp');

        if(!empty($vasseti->file_url)){
            $vasseti->file_url = $guizhou_cp[$vasseti->spid]['file_ftp'].$vasseti->file_url;
        }
        if(!empty($vasseti->pic0)){
            $vasseti->pic0 = $guizhou_cp[$vasseti->spid]['pic_ftp'].$vasseti->pic0;
        }
        if(!empty($vasseti->pic1)){
            $vasseti->pic1 = $guizhou_cp[$vasseti->spid]['pic_ftp'].$vasseti->pic1;
        }
        if(!empty($vasseti->pic2)){
            $vasseti->pic2 = $guizhou_cp[$vasseti->spid]['pic_ftp'].$vasseti->pic2;
        }
        if(!empty($vasseti->pic3)){
            $vasseti->pic3 = $guizhou_cp[$vasseti->spid]['pic_ftp'].$vasseti->pic3;
        }
        if(!empty($vasseti->pic4)){
            $vasseti->pic4 = $guizhou_cp[$vasseti->spid]['pic_ftp'].$vasseti->pic4;
        }
        if(!empty($vasseti->pic5)){
            $vasseti->pic5 = $guizhou_cp[$vasseti->spid]['pic_ftp'].$vasseti->pic5;
        }

        $action = empty($vasseti->inject_datetime) ? 'REGIST' : 'UPDATE';


        /**
         * xml生成
         */
        // 创建version标签$version=$doc->createElement("version");$versionTextNode=$doc->createTextNode("1.0");$version->appendchild($versionTextNode);当<root>标签中有值时就可以显示完整的<root>标签了
        // header("Content-type: text/xml"); //头文件非常重要
        // 创建xml文件, 建立DOM对象
        $dom = new \DOMDocument('1.0', 'UTF-8');
        // 格式化输出，友好地保留缩进和空格
        //$dom->formatOutput = true;

        // 建立<ADI>元素
        $adi = $dom->createElement('ADI');
        // 添加属性
        $adi->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
        // 把<ADI>元素追加到文档里面
        $dom->appendChild($adi);


        // 建立<Objects>对象
        $Objects = $dom->createElement('Objects');
        $adi->appendChild($Objects);

        // 建立<Series Objects>对象
        if(empty($vasseti->pid)){
            $SeriesObjects = $dom->createElement('Object');
            $SeriesObjects->setAttribute('ElementType', 'Series');
            $SeriesObjects->setAttribute('ID', $vasseti->spasset_id);
            $SeriesObjects->setAttribute('Action',$action);
            $SeriesObjects->setAttribute('Code', $vasseti->spasset_id);
            $Objects->appendChild($SeriesObjects);

            $Name = $dom->createElement('Property');
            $Name->setAttribute('Name', 'Name');
            $Name->textContent = $vasseti->title;
            $SeriesObjects->appendChild($Name);

            $AliasName = $dom->createElement('Property');
            $AliasName->setAttribute('Name', 'AliasName');
            $AliasName->textContent = $vasseti->subtitle;
            $SeriesObjects->appendChild($AliasName);

            $EnglishName = $dom->createElement('Property');
            $EnglishName->setAttribute('Name', 'EnglishName');
            $EnglishName->textContent = '';
            $SeriesObjects->appendChild($EnglishName);

            $WriterDisplay = $dom->createElement('Property');
            $WriterDisplay->setAttribute('Name', 'WriterDisplay');
            $WriterDisplay->textContent = str_replace(array(",","，"),"/",$vasseti->directors);
            $SeriesObjects->appendChild($WriterDisplay);

            $ActorDisplay = $dom->createElement('Property');
            $ActorDisplay->setAttribute('Name', 'ActorDisplay');
            $ActorDisplay->textContent = str_replace(array(",","，"),"/",$vasseti->actors);
            $SeriesObjects->appendChild($ActorDisplay);

            $Compere = $dom->createElement('Property');
            $Compere->setAttribute('Name', 'Compere');
            $Compere->textContent = '';
            $SeriesObjects->appendChild($Compere);

            $Type = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = $vasseti->vcat_id;
            $SeriesObjects->appendChild($Type);

            $Kind = $dom->createElement('Property');
            $Kind->setAttribute('Name', 'Kind');
            $Kind->textContent = str_replace(array(",","，"),"/",$vasseti->subvcat_id);
            $SeriesObjects->appendChild($Kind);

            $KeyWords = $dom->createElement('Property');
            $KeyWords->setAttribute('Name', 'KeyWords');
            $KeyWords->textContent = str_replace(array(",","，"),"/",$vasseti->tags);
            $SeriesObjects->appendChild($KeyWords);

            $OriginalCountry = $dom->createElement('Property');
            $OriginalCountry->setAttribute('Name', 'OriginalCountry');
            $OriginalCountry->textContent = $vasseti->varea;
            $SeriesObjects->appendChild($OriginalCountry);

            $ReleaseYear  = $dom->createElement('Property');
            $ReleaseYear->setAttribute('Name', 'ReleaseYear');
            $ReleaseYear->textContent = empty($vasseti->vyears) ? '' : date("Y-m-d",strtotime($vasseti->vyears));
            $SeriesObjects->appendChild($ReleaseYear);

            $VolumnCount  = $dom->createElement('Property');
            $VolumnCount->setAttribute('Name', 'VolumnCount');
            $VolumnCount->textContent = $vasseti->serials;
            $SeriesObjects->appendChild($VolumnCount);

            $Description = $dom->createElement('Property');
            $Description->setAttribute('Name', 'Description');
            $Description->textContent = $vasseti->short_desc ? $vasseti->short_desc : $vasseti->long_desc;
            $SeriesObjects->appendChild($Description);

            $ContentProvider  = $dom->createElement('Property');
            $ContentProvider->setAttribute('Name', 'ContentProvider');
            $ContentProvider->textContent = $guizhou_cp[$vasseti->spid]['cpid'];
            $SeriesObjects->appendChild($ContentProvider);

            $Duration  = $dom->createElement('Property');
            $Duration->setAttribute('Name', 'Duration');
            $Duration->textContent = $vasseti->duration;
            $SeriesObjects->appendChild($Duration);

            $Language  = $dom->createElement('Property');
            $Language->setAttribute('Name', 'Language');
            $Language->textContent = $vasseti->vlang;
            $SeriesObjects->appendChild($Language);


            $PlayCount  = $dom->createElement('Property');
            $PlayCount->setAttribute('Name', 'PlayCount');
            $PlayCount->textContent = '';
            $SeriesObjects->appendChild($PlayCount);

            $Copyright  = $dom->createElement('Property');
            $Copyright->setAttribute('Name', 'Copyright');
            $Copyright->textContent = '';
            $SeriesObjects->appendChild($Copyright);

            $LicensingWindowStart  = $dom->createElement('Property');
            $LicensingWindowStart->setAttribute('Name', 'LicensingWindowStart');
            $LicensingWindowStart->textContent = '';
            $SeriesObjects->appendChild($LicensingWindowStart);

            $LicensingWindowEnd  = $dom->createElement('Property');
            $LicensingWindowEnd->setAttribute('Name', 'LicensingWindowEnd');
            $LicensingWindowEnd->textContent = '';
            $SeriesObjects->appendChild($LicensingWindowEnd);

            $ParentCategoryId  = $dom->createElement('Property');
            $ParentCategoryId->setAttribute('Name', 'ParentCategoryId');
            $ParentCategoryId->textContent = '';
            $SeriesObjects->appendChild($ParentCategoryId);

            $ParentCategoryName   = $dom->createElement('Property');
            $ParentCategoryName->setAttribute('Name', 'ParentCategoryName');
            $ParentCategoryName->textContent = '';
            $SeriesObjects->appendChild($ParentCategoryName);

            $OnlineIdentify  = $dom->createElement('Property');
            $OnlineIdentify->setAttribute('Name', 'OnlineIdentify');
            $OnlineIdentify->textContent = '';
            $SeriesObjects->appendChild($OnlineIdentify);
        }
        //如果是电影或者电视剧剧集
        if($vasseti->file_url){
            // 建立<Program Objects>对象
            $ProgramObjects = $dom->createElement('Object');
            $ProgramObjects->setAttribute('ElementType', 'Program');
            $ProgramObjects->setAttribute('ID', 'program'.$vasseti->spasset_id);
            $ProgramObjects->setAttribute('Action', $action);
            $ProgramObjects->setAttribute('Code', 'program'.$vasseti->spasset_id);
            $Objects->appendChild($ProgramObjects);

            $Name  = $dom->createElement('Property');
            $Name->setAttribute('Name', 'Name');
            $Name->textContent = $vasseti->title;
            $ProgramObjects->appendChild($Name);

            $Duration  = $dom->createElement('Property');
            $Duration->setAttribute('Name', 'Duration');
            $Duration->textContent = $vasseti->duration;
            $ProgramObjects->appendChild($Duration);

            $Description = $dom->createElement('Property');
            $Description->setAttribute('Name', 'Description');
            $Description->textContent = $vasseti->short_desc ? $vasseti->short_desc : $vasseti->long_desc;
            $ProgramObjects->appendChild($Description);

            $WriterDisplay = $dom->createElement('Property');
            $WriterDisplay->setAttribute('Name', 'WriterDisplay');
            $WriterDisplay->textContent = str_replace(array(",","，"),"/",$vasseti->directors);
            $ProgramObjects->appendChild($WriterDisplay);

            $ActorDisplay = $dom->createElement('Property');
            $ActorDisplay->setAttribute('Name', 'ActorDisplay');
            $ActorDisplay->textContent = str_replace(array(",","，"),"/",$vasseti->actors);
            $ProgramObjects->appendChild($ActorDisplay);

            $ReleaseYear  = $dom->createElement('Property');
            $ReleaseYear->setAttribute('Name', 'ReleaseYear');
            $ReleaseYear->textContent = empty($vasseti->vyears) ? '' : date("Y-m-d",strtotime($vasseti->vyears));
            $ProgramObjects->appendChild($ReleaseYear);

            $WatchFocus  = $dom->createElement('Property');
            $WatchFocus->setAttribute('Name', 'WatchFocus');
            $WatchFocus->textContent = '';
            $ProgramObjects->appendChild($WatchFocus);

            $OriginalName  = $dom->createElement('Property');
            $OriginalName->setAttribute('Name', 'OriginalName');
            $OriginalName->textContent = $vasseti->subtitle;
            $ProgramObjects->appendChild($OriginalName);

            $OriginalCountry  = $dom->createElement('Property');
            $OriginalCountry->setAttribute('Name', 'OriginalCountry');
            $OriginalCountry->textContent = $vasseti->varea;
            $ProgramObjects->appendChild($OriginalCountry);

            $Language  = $dom->createElement('Property');
            $Language->setAttribute('Name', 'Language');
            $Language->textContent = $vasseti->vlang;
            $ProgramObjects->appendChild($Language);

            $KeyWords = $dom->createElement('Property');
            $KeyWords->setAttribute('Name', 'KeyWords');
            $KeyWords->textContent = str_replace(array(",","，"),"/",$vasseti->tags);
            $ProgramObjects->appendChild($KeyWords);

            // 建立<Movie Objects>对象
            $movieObjects = $dom->createElement('Object');
            $movieObjects->setAttribute('ElementType', 'Movie');
            $movieObjects->setAttribute('ID', $vasseti->sp_file_id);
            $movieObjects->setAttribute('Action', $action);
            $movieObjects->setAttribute('Code', $vasseti->sp_file_id);
            $Objects->appendChild($movieObjects);


            $Name  = $dom->createElement('Property');
            $Name->setAttribute('Name', 'Name');
            $Name->textContent = $vasseti->title;
            $movieObjects->appendChild($Name);

            $Duration  = $dom->createElement('Property');
            $Duration->setAttribute('Name', 'Duration');
            $Duration->textContent = $vasseti->duration;
            $movieObjects->appendChild($Duration);

            $SystemLayer  = $dom->createElement('Property');
            $SystemLayer->setAttribute('Name', 'SystemLayer');
            $SystemLayer->textContent = $vasseti->vformat;
            $movieObjects->appendChild($SystemLayer);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = '1';
            $movieObjects->appendChild($Type);

            $FileURL  = $dom->createElement('Property');
            $FileURL->setAttribute('Name', 'FileURL');
            $FileURL->textContent = $vasseti->file_url;
            $movieObjects->appendChild($FileURL);

            $MediaMode  = $dom->createElement('Property');
            $MediaMode->setAttribute('Name', 'MediaMode');
            $MediaMode->textContent = $vasseti->resolutions;
            $movieObjects->appendChild($MediaMode);

            $Resolution  = $dom->createElement('Property');
            $Resolution->setAttribute('Name', 'Resolution');
            $Resolution->textContent = '';
            $movieObjects->appendChild($Resolution);

            $FileSize  = $dom->createElement('Property');
            $FileSize->setAttribute('Name', 'FileSize');
            $FileSize->textContent = '';
            $movieObjects->appendChild($FileSize);

            $BitRateType  = $dom->createElement('Property');
            $BitRateType->setAttribute('Name', 'BitRateType');
            $BitRateType->textContent = $vasseti->vbitate;
            $movieObjects->appendChild($BitRateType);

            $Tag  = $dom->createElement('Property');
            $Tag->setAttribute('Name', 'Tag');
            $Tag->textContent = '';
            $movieObjects->appendChild($Tag);

            $MediaType  = $dom->createElement('Property');
            $MediaType->setAttribute('Name', 'MediaType');
            $MediaType->textContent = $vasseti->mediatype;
            $movieObjects->appendChild($MediaType);

            $LiveId  = $dom->createElement('Property');
            $LiveId->setAttribute('Name', 'LiveId');
            $LiveId->textContent = '';
            $movieObjects->appendChild($LiveId);

            $BeginTime  = $dom->createElement('Property');
            $BeginTime->setAttribute('Name', 'BeginTime');
            $BeginTime->textContent = '';
            $movieObjects->appendChild($BeginTime);


            // 建立<Mappings>对象
            $Mappings = $dom->createElement('Mappings');
            $adi->appendChild($Mappings);
            // 建立<Program Mapping>对象
            $ProgrammappingObjects = $dom->createElement('Mapping');
            $ProgrammappingObjects->setAttribute('ParentType', 'Series');
            $ProgrammappingObjects->setAttribute('ElementType', 'Program');
            $ProgrammappingObjects->setAttribute('ParentID', ($vasseti->pid ? $vasseti->pid : $vasseti->spasset_id));
            $ProgrammappingObjects->setAttribute('ElementID', 'program'.$vasseti->spasset_id);
            $ProgrammappingObjects->setAttribute('ElementCode', 'program'.$vasseti->spasset_id);
            $ProgrammappingObjects->setAttribute('ParentCode', $vasseti->spasset_id);

            $Sequence  = $dom->createElement('Property');
            $Sequence->setAttribute('Name', 'Sequence');
            $Sequence->textContent = empty($vasseti->episode) ? 0 : ($vasseti->episode-1);
            $ProgrammappingObjects->appendChild($Sequence);

            $Mappings->appendChild($ProgrammappingObjects);
            // 建立<Movie Mapping>对象
            $MoviemappingObjects = $dom->createElement('Mapping');
            $MoviemappingObjects->setAttribute('ParentType', 'Program');
            $MoviemappingObjects->setAttribute('ElementType', 'Movie');
            $MoviemappingObjects->setAttribute('ParentID', 'program'.$vasseti->spasset_id);
            $MoviemappingObjects->setAttribute('ElementID', $vasseti->sp_file_id);
            $MoviemappingObjects->setAttribute('ElementCode', $vasseti->sp_file_id);
            $MoviemappingObjects->setAttribute('ParentCode', 'program'.$vasseti->spasset_id);

            $Mappings->appendChild($MoviemappingObjects);

        }else{
            // 建立<Mappings>对象
            $Mappings = $dom->createElement('Mappings');
            $adi->appendChild($Mappings);

        }

        if(!empty($vasseti->pic0)){
            // 建立<Movie Objects>对象
            $picObjects = $dom->createElement('Object');
            $picObjects->setAttribute('ElementType', 'Picture');
            $picObjects->setAttribute('ID', 'pic0'.$vasseti->spasset_id);
            $picObjects->setAttribute('Action', $action);
            $picObjects->setAttribute('Code', 'pic0'.$vasseti->spasset_id);
            $Objects->appendChild($picObjects);

            $FileURL  = $dom->createElement('Property');
            $FileURL->setAttribute('Name', 'FileURL');
            $FileURL->textContent = $vasseti->pic0;
            $picObjects->appendChild($FileURL);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = '0';
            $picObjects->appendChild($Type);
        }

        if(!empty($vasseti->pic1)){
            // 建立<Movie Objects>对象
            $picObjects = $dom->createElement('Object');
            $picObjects->setAttribute('ElementType', 'Picture');
            $picObjects->setAttribute('ID', 'pic1'.$vasseti->spasset_id);
            $picObjects->setAttribute('Action', $action);
            $picObjects->setAttribute('Code', 'pic1'.$vasseti->spasset_id);
            $Objects->appendChild($picObjects);

            $FileURL  = $dom->createElement('Property');
            $FileURL->setAttribute('Name', 'FileURL');
            $FileURL->textContent = $vasseti->pic1;
            $picObjects->appendChild($FileURL);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = '1';
            $picObjects->appendChild($Type);
        }

        if(!empty($vasseti->pic2)){
            // 建立<Movie Objects>对象
            $picObjects = $dom->createElement('Object');
            $picObjects->setAttribute('ElementType', 'Picture');
            $picObjects->setAttribute('ID', 'pic2'.$vasseti->spasset_id);
            $picObjects->setAttribute('Action', $action);
            $picObjects->setAttribute('Code', 'pic2'.$vasseti->spasset_id);
            $Objects->appendChild($picObjects);

            $FileURL  = $dom->createElement('Property');
            $FileURL->setAttribute('Name', 'FileURL');
            $FileURL->textContent = $vasseti->pic2;
            $picObjects->appendChild($FileURL);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = '2';
            $picObjects->appendChild($Type);
        }

        if(!empty($vasseti->pic3)){
            // 建立<Movie Objects>对象
            $picObjects = $dom->createElement('Object');
            $picObjects->setAttribute('ElementType', 'Picture');
            $picObjects->setAttribute('ID', 'pic3'.$vasseti->spasset_id);
            $picObjects->setAttribute('Action', $action);
            $picObjects->setAttribute('Code', 'pic3'.$vasseti->spasset_id);
            $Objects->appendChild($picObjects);

            $FileURL  = $dom->createElement('Property');
            $FileURL->setAttribute('Name', 'FileURL');
            $FileURL->textContent = $vasseti->pic3;
            $picObjects->appendChild($FileURL);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = '3';
            $picObjects->appendChild($Type);
        }


        if(!empty($vasseti->pic4)){
            // 建立<Movie Objects>对象
            $picObjects = $dom->createElement('Object');
            $picObjects->setAttribute('ElementType', 'Picture');
            $picObjects->setAttribute('ID', 'pic4'.$vasseti->spasset_id);
            $picObjects->setAttribute('Action', $action);
            $picObjects->setAttribute('Code', 'pic4'.$vasseti->spasset_id);
            $Objects->appendChild($picObjects);

            $FileURL  = $dom->createElement('Property');
            $FileURL->setAttribute('Name', 'FileURL');
            $FileURL->textContent = $vasseti->pic4;
            $picObjects->appendChild($FileURL);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = '4';
            $picObjects->appendChild($Type);
        }


        if(!empty($vasseti->pic5)){
            // 建立<Movie Objects>对象
            $picObjects = $dom->createElement('Object');
            $picObjects->setAttribute('ElementType', 'Picture');
            $picObjects->setAttribute('ID', 'pic5'.$vasseti->spasset_id);
            $picObjects->setAttribute('Action', $action);
            $picObjects->setAttribute('Code', 'pic5'.$vasseti->spasset_id);
            $Objects->appendChild($picObjects);

            $FileURL  = $dom->createElement('Property');
            $FileURL->setAttribute('Name', 'FileURL');
            $FileURL->textContent = $vasseti->pic5;
            $picObjects->appendChild($FileURL);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = '5';
            $picObjects->appendChild($Type);
        }

        if(!empty($vasseti->pic0)){
            // 建立<Picture Mapping>对象
            $picmappingObjects = $dom->createElement('Mapping');
            $picmappingObjects->setAttribute('ParentType', 'Picture');
            $picmappingObjects->setAttribute('ElementType', 'Series');
            $picmappingObjects->setAttribute('ParentID', 'pic0'.$vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementID', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementCode', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ParentCode', 'pic0'.$vasseti->spasset_id);

            $Sequence  = $dom->createElement('Property');
            $Sequence->setAttribute('Name', 'Sequence');
            $Sequence->textContent = 0;
            $picmappingObjects->appendChild($Sequence);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = 0;
            $picmappingObjects->appendChild($Type);

            $Mappings->appendChild($picmappingObjects);
        }

        if(!empty($vasseti->pic1)){
            // 建立<Picture Mapping>对象
            $picmappingObjects = $dom->createElement('Mapping');
            $picmappingObjects->setAttribute('ParentType', 'Picture');
            $picmappingObjects->setAttribute('ElementType', 'Series');
            $picmappingObjects->setAttribute('ParentID', 'pic1'.$vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementID', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementCode', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ParentCode', 'pic1'.$vasseti->spasset_id);

            $Sequence  = $dom->createElement('Property');
            $Sequence->setAttribute('Name', 'Sequence');
            $Sequence->textContent = 0;
            $picmappingObjects->appendChild($Sequence);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = 1;
            $picmappingObjects->appendChild($Type);

            $Mappings->appendChild($picmappingObjects);
        }

        if(!empty($vasseti->pic2)){
            // 建立<Picture Mapping>对象
            $picmappingObjects = $dom->createElement('Mapping');
            $picmappingObjects->setAttribute('ParentType', 'Picture');
            $picmappingObjects->setAttribute('ElementType', 'Series');
            $picmappingObjects->setAttribute('ParentID', 'pic2'.$vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementID', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementCode', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ParentCode', 'pic2'.$vasseti->spasset_id);

            $Sequence  = $dom->createElement('Property');
            $Sequence->setAttribute('Name', 'Sequence');
            $Sequence->textContent = 0;
            $picmappingObjects->appendChild($Sequence);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = 2;
            $picmappingObjects->appendChild($Type);

            $Mappings->appendChild($picmappingObjects);
        }


        if(!empty($vasseti->pic3)){
            // 建立<Picture Mapping>对象
            $picmappingObjects = $dom->createElement('Mapping');
            $picmappingObjects->setAttribute('ParentType', 'Picture');
            $picmappingObjects->setAttribute('ElementType', 'Series');
            $picmappingObjects->setAttribute('ParentID', 'pic3'.$vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementID', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementCode', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ParentCode', 'pic3'.$vasseti->spasset_id);

            $Sequence  = $dom->createElement('Property');
            $Sequence->setAttribute('Name', 'Sequence');
            $Sequence->textContent = 0;
            $picmappingObjects->appendChild($Sequence);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = 3;
            $picmappingObjects->appendChild($Type);

            $Mappings->appendChild($picmappingObjects);
        }


        if(!empty($vasseti->pic4)){
            // 建立<Picture Mapping>对象
            $picmappingObjects = $dom->createElement('Mapping');
            $picmappingObjects->setAttribute('ParentType', 'Picture');
            $picmappingObjects->setAttribute('ElementType', 'Series');
            $picmappingObjects->setAttribute('ParentID', 'pic4'.$vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementID', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementCode', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ParentCode', 'pic4'.$vasseti->spasset_id);

            $Sequence  = $dom->createElement('Property');
            $Sequence->setAttribute('Name', 'Sequence');
            $Sequence->textContent = 0;
            $picmappingObjects->appendChild($Sequence);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = 4;
            $picmappingObjects->appendChild($Type);

            $Mappings->appendChild($picmappingObjects);
        }

        if(!empty($vasseti->pic5)){
            // 建立<Picture Mapping>对象
            $picmappingObjects = $dom->createElement('Mapping');
            $picmappingObjects->setAttribute('ParentType', 'Picture');
            $picmappingObjects->setAttribute('ElementType', 'Series');
            $picmappingObjects->setAttribute('ParentID', 'pic5'.$vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementID', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ElementCode', $vasseti->spasset_id);
            $picmappingObjects->setAttribute('ParentCode', 'pic5'.$vasseti->spasset_id);

            $Sequence  = $dom->createElement('Property');
            $Sequence->setAttribute('Name', 'Sequence');
            $Sequence->textContent = 0;
            $picmappingObjects->appendChild($Sequence);

            $Type  = $dom->createElement('Property');
            $Type->setAttribute('Name', 'Type');
            $Type->textContent = 5;
            $picmappingObjects->appendChild($Type);

            $Mappings->appendChild($picmappingObjects);
        }

        $xml = $dom->saveXML();

        return $xml;
    }

}
